package it.evento.manager;

import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.CalendarListEntry;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.api.services.calendar.model.Events;
import java.io.IOException;
import java.util.Date;
import java.util.TimeZone;

/**
 *
 * @author Mark
 */
public class CalendarManager {

    private static Calendar service;
    private static OAuthManager oam = new OAuthManager();
    String pageToken = null; 

    /**
     * Create a new authorized API client
     */
    public CalendarManager(){
        service = new Calendar.Builder(oam.getHttpTransport(), oam.getJsonFactory(), oam.getCredential())
                .setApplicationName("ProgettoEventTo")
                .build();        
    }
    /**
     * Crea calendario della nostra applicazione, EvenTO, dove inserire gli eventi a cui l'utente si iscrive
     * @throws IOException 
     */
    public com.google.api.services.calendar.model.Calendar createEventoCalendar() throws IOException{
       com.google.api.services.calendar.model.Calendar newCalendar = new com.google.api.services.calendar.model.Calendar();
       newCalendar.setSummary("EvenTo");
       newCalendar.setLocation("Torino");
 
       com.google.api.services.calendar.model.Calendar eventoCalendar = service.calendars().insert(newCalendar).execute();
       
       System.out.println("createEventoCalendar - Calendar ID: "+eventoCalendar.getId());
       return eventoCalendar;
               
    }
    /**
     * Crea un evento sul calendario che gli viene passato in input
     * @param eventoCalendar
     * @param nomeEv
     * @param locEv
     * @param startD
     * @param endD
     * @return
     * @throws IOException 
     */
    public String createEvent(com.google.api.services.calendar.model.Calendar eventoCalendar, String nomeEv, String locEv, Date startD,Date endD) throws IOException{
            //System.out.println("calendar service: " + service.toString() + " (" + service.getApplicationName() + ")");
            Event event = new Event();
            event.setSummary(nomeEv);
            event.setLocation(locEv);
    
            DateTime start = new DateTime(startD, TimeZone.getTimeZone("UTC"));
            event.setStart(new EventDateTime().setDateTime(start));
            DateTime end = new DateTime(endD, TimeZone.getTimeZone("UTC"));
            event.setEnd(new EventDateTime().setDateTime(end));

            //Event insertedEvent = service.events().insert("primary", event).execute();
            Event insertedEvent = service.events().insert(eventoCalendar.getId(), event).execute();
            return insertedEvent.getId();

            //System.out.println("new event id: " + insertedEvent.getId());
    }
    
   /**
    * Restituisce la lista degli eventi di uno dei calendari dell'utente passato come parametro
    * @param eventoCalendar
    * @return
    * @throws IOException 
    */
    public java.util.List<Event> getUserEvents(com.google.api.services.calendar.model.Calendar eventoCalendar) throws IOException{
        //do {
          Events events = service.events().list(eventoCalendar.getId()).setPageToken(pageToken).execute();
          java.util.List<Event> items = events.getItems();
          return items;
          /*
          for (Event event : items) {
            System.out.println("evento trovato: "+event.getSummary());
          }*/
         // pageToken = events.getNextPageToken();
        //} while (pageToken != null);

   
    }
    /**
     * Ottiene la lista dei calendari dell'utente corrente (che si è autenticato su google)
     * @return
     * @throws IOException 
     */
    public java.util.List<CalendarListEntry> getUserCalendars() throws IOException{
        com.google.api.services.calendar.model.CalendarList calendarList = service.calendarList().list().setPageToken(pageToken).execute();
        java.util.List<CalendarListEntry> items = calendarList.getItems();
        return items;
    }
    /**
     * Inizializza il calendario dell'utente:
     *  se non esiste il calendario EvenTo -> crea calendario Evento
     *  altrimenti restituisce quello gia' presente
     * @return
     * @throws IOException 
     */
    public  com.google.api.services.calendar.model.Calendar inizializeUserCalendar() throws IOException{
        java.util.List<CalendarListEntry> calendars = getUserCalendars();

        for (CalendarListEntry calendarListEntry : calendars) {        
          if(calendarListEntry.getSummary().equals("EvenTo")){
              return service.calendars().get(calendarListEntry.getId()).execute();              
          }
        } 
        return createEventoCalendar();
       
    }
    
}
